<template>
  <div class="manager-management">
    <!-- 页面头部导航 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="primary" 
          icon="ArrowLeft" 
          @click="$router.back()"
          class="back-btn"
        >
          返回
        </el-button>
        <div class="page-info">
          <h2>店长管理</h2>
          <p>管理系统中所有店长账户的信息</p>
        </div>
      </div>
      
      <div class="header-right">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="navigateToHome" class="breadcrumb-link">控制台</el-breadcrumb-item>
          <el-breadcrumb-item>店长管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button 
        type="primary" 
        icon="Plus" 
        @click="showCreateDialog = true"
      >
        新建店长账户
      </el-button>
      
      <div class="toolbar-right">
        <el-select 
          v-model="shopFilter" 
          placeholder="按店铺筛选" 
          clearable
          @change="handleShopFilter"
        >
          <el-option 
            v-for="shop in shopsForFilter" 
            :key="shop.id" 
            :label="shop.name" 
            :value="shop.id" 
          />
        </el-select>
        
        <el-select 
          v-model="statusFilter" 
          placeholder="按状态筛选" 
          clearable
          @change="handleStatusFilter"
        >
          <el-option label="正常" value="active" />
          <el-option label="停用" value="inactive" />
          <el-option label="锁定" value="locked" />
        </el-select>
        
        <el-button 
          icon="Refresh" 
          @click="loadManagers"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 店长列表表格 -->
    <el-table 
      :data="managersData" 
      v-loading="loading"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column prop="username" label="用户名" width="140" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="shopName" label="所属店铺" min-width="160" />
      <el-table-column prop="phone" label="手机号" width="140" />
      <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
      <el-table-column prop="status" label="账户状态" width="100">
        <template #default="{ row }">
          <el-tag 
            :type="getStatusType(row.status)"
            size="small"
          >
            {{ row.statusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="最后登录" width="160">
        <template #default="{ row }">
          {{ formatTime(row.lastLoginTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          
          <el-dropdown @command="(command) => handleStatusChange(row, command)">
            <el-button type="warning" size="small" text>
              状态 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  command="active" 
                  :disabled="row.status === 'active'"
                >
                  启用
                </el-dropdown-item>
                <el-dropdown-item 
                  command="inactive" 
                  :disabled="row.status === 'inactive'"
                >
                  停用
                </el-dropdown-item>
                <el-dropdown-item 
                  command="locked" 
                  :disabled="row.status === 'locked'"
                >
                  锁定
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-button 
            type="success" 
            size="small" 
            text
            @click="handleResetPassword(row)"
          >
            重置密码
          </el-button>
          
          <el-button 
            type="danger" 
            size="small" 
            text
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建店长账户对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建店长账户" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="createFormRef" 
        :model="createForm" 
        :rules="createRules" 
        label-width="100px"
      >
        <el-form-item label="所属店铺" prop="shopId">
          <el-select 
            v-model="createForm.shopId" 
            placeholder="请选择店铺"
            style="width: 100%"
          >
            <el-option 
              v-for="shop in availableShops" 
              :key="shop.id" 
              :label="shop.name" 
              :value="shop.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="createForm.username" 
            placeholder="请输入用户名（3-50字符，字母数字下划线）"
            maxlength="50"
            show-word-limit
            @blur="checkUsername"
          />
          <div class="form-tip">用户名用于登录，创建后不可修改</div>
        </el-form-item>
        
        <el-form-item label="初始密码" prop="password">
          <el-input 
            v-model="createForm.password" 
            type="password" 
            placeholder="请输入初始密码（6-50字符）"
            maxlength="50"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input 
            v-model="createForm.realName" 
            placeholder="请输入真实姓名（2-100字符）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="createForm.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="createForm.email" 
            placeholder="请输入邮箱地址"
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreate"
          :loading="createLoading"
        >
          创建账户
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑店长信息对话框 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑店长信息" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        :rules="editRules" 
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input :value="currentManager?.username" disabled />
          <div class="form-tip">用户名不可修改</div>
        </el-form-item>
        
        <el-form-item label="所属店铺">
          <el-input :value="currentManager?.shopName" disabled />
          <div class="form-tip">所属店铺不可修改</div>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input 
            v-model="editForm.realName" 
            placeholder="请输入真实姓名（2-100字符）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="editForm.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="editForm.email" 
            placeholder="请输入邮箱地址"
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleUpdate"
          :loading="updateLoading"
        >
          保存修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog 
      v-model="showPasswordDialog" 
      title="重置密码" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="passwordFormRef" 
        :model="passwordForm" 
        :rules="passwordRules" 
        label-width="80px"
      >
        <el-form-item label="用户">
          <el-input :value="currentManager?.realName + ' (' + currentManager?.username + ')'" disabled />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码（6-50字符）"
            maxlength="50"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            maxlength="50"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handlePasswordReset"
          :loading="passwordLoading"
        >
          重置密码
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
import { 
  adminManagerApi, 
  adminShopApi, 
  type Manager, 
  type Shop, 
  type CreateManagerParams, 
  type UpdateManagerParams 
} from '@renderer/api/admin'

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const updateLoading = ref(false)
const passwordLoading = ref(false)
const managersData = ref<Manager[]>([])
const availableShops = ref<Shop[]>([])
const shopsForFilter = ref<Shop[]>([])
const shopFilter = ref<number | ''>('')
const statusFilter = ref<string>('')

// 对话框显示状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const currentManager = ref<Manager | null>(null)

// 表单引用
const createFormRef = ref<InstanceType<typeof ElForm>>()
const editFormRef = ref<InstanceType<typeof ElForm>>()
const passwordFormRef = ref<InstanceType<typeof ElForm>>()

// 创建表单
const createForm = reactive<CreateManagerParams>({
  shopId: undefined as any, // 初始不选择，强制用户选择
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: ''
})

// 编辑表单
const editForm = reactive<UpdateManagerParams>({
  id: 0,
  realName: '',
  phone: '',
  email: ''
})

// 密码重置表单
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 验证确认密码
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const createRules = {
  shopId: [
    { required: true, message: '请选择所属店铺', trigger: 'change' },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value === 0) {
          callback(new Error('请选择有效的店铺'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度应为3-50字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母数字下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入初始密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度应为6-50字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 100, message: '真实姓名长度应为2-100字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

const editRules = {
  realName: [
    { min: 2, max: 100, message: '真实姓名长度应为2-100字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度应为6-50字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 加载店长列表
const loadManagers = async () => {
  try {
    loading.value = true
    const response = await adminManagerApi.getManagers()
    managersData.value = response.data.data
  } catch (error) {
    console.error('加载店长列表失败:', error)
    ElMessage.error('加载店长列表失败')
  } finally {
    loading.value = false
  }
}

// 加载店铺列表
const loadShops = async () => {
  try {
    const response = await adminShopApi.getShops()
    const shops = response.data.data.filter(shop => shop.status === 'active')
    availableShops.value = shops
    shopsForFilter.value = response.data.data
  } catch (error) {
    console.error('加载店铺列表失败:', error)
    ElMessage.error('加载店铺列表失败')
  }
}

// 按店铺筛选
const handleShopFilter = async () => {
  if (!shopFilter.value) {
    await loadManagers()
    return
  }
  
  try {
    loading.value = true
    const response = await adminManagerApi.getManagersByShopId(shopFilter.value as number)
    managersData.value = response.data.data
  } catch (error) {
    console.error('按店铺筛选失败:', error)
    ElMessage.error('筛选失败')
  } finally {
    loading.value = false
  }
}

// 按状态筛选
const handleStatusFilter = async () => {
  if (!statusFilter.value) {
    await loadManagers()
    return
  }
  
  try {
    loading.value = true
    const response = await adminManagerApi.getManagersByStatus(statusFilter.value as any)
    managersData.value = response.data.data
  } catch (error) {
    console.error('按状态筛选失败:', error)
    ElMessage.error('筛选失败')
  } finally {
    loading.value = false
  }
}

// 检查用户名
const checkUsername = async () => {
  if (!createForm.username) return
  
  try {
    const response = await adminManagerApi.checkUsername(createForm.username)
    if (response.data.data) {
      ElMessage.warning('该用户名已存在，请使用其他用户名')
    }
  } catch (error) {
    console.error('检查用户名失败:', error)
  }
}

// 创建店长账户
const handleCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    createLoading.value = true
    
    // 验证表单数据
    if (!createForm.shopId || createForm.shopId === 0) {
      ElMessage.error('请选择有效的店铺')
      return
    }
    
    // 清理空字符串字段，避免后端验证失败
    const submitData = {
      shopId: createForm.shopId,
      username: createForm.username,
      password: createForm.password,
      realName: createForm.realName,
      ...(createForm.phone && createForm.phone.trim() ? { phone: createForm.phone.trim() } : {}),
      ...(createForm.email && createForm.email.trim() ? { email: createForm.email.trim() } : {})
    }
    
    console.log('准备创建店长账户，数据:', submitData)
    
    await adminManagerApi.createManager(submitData)
    ElMessage.success('店长账户创建成功')
    
    showCreateDialog.value = false
    resetCreateForm()
    await loadManagers()
    
  } catch (error: any) {
    console.error('创建店长账户失败:', error)
    
    // 处理不同类型的错误
    if (error?.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error?.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建店长账户失败，请稍后重试')
    }
  } finally {
    createLoading.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    shopId: undefined as any,
    username: '',
    password: '',
    realName: '',
    phone: '',
    email: ''
  })
  createFormRef.value?.resetFields()
}

// 编辑店长
const handleEdit = (manager: Manager) => {
  currentManager.value = manager
  Object.assign(editForm, {
    id: manager.id,
    realName: manager.realName,
    phone: manager.phone,
    email: manager.email
  })
  showEditDialog.value = true
}

// 更新店长信息
const handleUpdate = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    updateLoading.value = true
    
    // 清理空字符串字段
    const submitData = {
      id: editForm.id,
      realName: editForm.realName,
      ...(editForm.phone && editForm.phone.trim() ? { phone: editForm.phone.trim() } : {}),
      ...(editForm.email && editForm.email.trim() ? { email: editForm.email.trim() } : {})
    }
    
    await adminManagerApi.updateManager(submitData)
    ElMessage.success('店长信息更新成功')
    
    showEditDialog.value = false
    await loadManagers()
    
  } catch (error: any) {
    console.error('更新店长信息失败:', error)
    
    // 处理不同类型的错误
    if (error?.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error?.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('更新店长信息失败，请稍后重试')
    }
  } finally {
    updateLoading.value = false
  }
}

// 状态变更
const handleStatusChange = async (manager: Manager, newStatus: string) => {
  try {
    await ElMessageBox.confirm(
      `确认将店长"${manager.realName}"的状态变更为${getStatusName(newStatus)}吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await adminManagerApi.updateManagerStatus(manager.id, newStatus as any)
    ElMessage.success('店长状态更新成功')
    await loadManagers()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新店长状态失败:', error)
      ElMessage.error('状态更新失败')
    }
  }
}

// 重置密码
const handleResetPassword = (manager: Manager) => {
  currentManager.value = manager
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  showPasswordDialog.value = true
}

// 执行密码重置
const handlePasswordReset = async () => {
  if (!passwordFormRef.value || !currentManager.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    await adminManagerApi.resetManagerPassword(currentManager.value.id, passwordForm.newPassword)
    ElMessage.success('密码重置成功')
    
    showPasswordDialog.value = false
    
  } catch (error) {
    console.error('重置密码失败:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    passwordLoading.value = false
  }
}

// 删除店长账户
const handleDelete = async (manager: Manager) => {
  try {
    await ElMessageBox.confirm(
      `确认删除店长账户"${manager.realName} (${manager.username})"吗？此操作会影响相关数据，无法恢复！`,
      '危险操作',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error',
        buttonSize: 'default'
      }
    )
    
    await adminManagerApi.deleteManager(manager.id)
    ElMessage.success('店长账户删除成功')
    await loadManagers()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除店长账户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'active': 'success',
    'inactive': 'warning',
    'locked': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const names: Record<string, string> = {
    'active': '正常',
    'inactive': '停用',
    'locked': '锁定'
  }
  return names[status] || '未知'
}

// 格式化时间
const formatTime = (timeStr: string | null) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 导航到首页
const navigateToHome = () => {
  router.push('/admin/dashboard')
}

// 页面加载
onMounted(() => {
  loadManagers()
  loadShops()
})
</script>

<style scoped lang="scss">
.manager-management {
  padding: 20px;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .back-btn {
        border-radius: 8px;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
      
      .page-info {
        h2 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
    
    .header-right {
      .breadcrumb-link {
        cursor: pointer;
        color: #409eff;
        
        &:hover {
          color: #66b1ff;
        }
      }
    }
  }
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .toolbar-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

.el-table {
  margin-bottom: 20px;
}

.el-dialog {
  .el-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}
</style>